package cn.dalgen.mybatis.gen.utils.db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import cn.dalgen.mybatis.gen.model.db.DataBase;
import com.alibaba.druid.pool.DruidDataSource;

public class DruidUtils {
    private static DruidDataSource dataSource;
    /**
     * 获取数据源
     *
     * @param currentDb
     * @return
     * @throws SQLException
     * @throws IOException
     */
    public static DataSource getDataSource(DataBase currentDb) {
        return getDataSource(currentDb.getDriverClass(), currentDb.getPropertyMapVal("url"),
            currentDb.getPropertyMapVal("userid"), currentDb.getPropertyMapVal("password"));
    }

    /**
     * 获取数据源
     *
     * @return
     * @throws SQLException
     * @throws IOException
     */
    private static DataSource getDataSource(String driverClassName, String jdbcUrl, String username, String password) {
        // 因为dataSource是全局变量、默认初始化值为null
        if (dataSource == null) {
            dataSource = new DruidDataSource();
            dataSource.setUrl(jdbcUrl);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            dataSource.setDriverClassName(driverClassName);
            dataSource.setMaxActive(20);
            dataSource.setInitialSize(1);
            dataSource.setMaxWait(6000);
            dataSource.setMinIdle(1);
            dataSource.setTimeBetweenEvictionRunsMillis(60000);
            dataSource.setMinEvictableIdleTimeMillis(300000);
            dataSource.setTestWhileIdle(true);
            dataSource.setTestOnBorrow(false);
            dataSource.setTestOnReturn(false);
            dataSource.setPoolPreparedStatements(true);
            dataSource.setMaxOpenPreparedStatements(20);
            dataSource.setAsyncInit(true);
            try {
                dataSource.init();
            } catch (SQLException e) {
               throw new RuntimeException(e);
            }
        }
        // 返回dataSource
        return dataSource;
    }
    /**
     * 通过数据源获取连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public static void close() {
        if (dataSource != null) {
            dataSource.close();
            dataSource=null;
        }
    }
}
